/**
 * Created by Panda on 16/8/22
 */
(function () {
    'use strict';

    /**
     * 校验的函数，返回true表示data合法，否则不合法
     * */
    var ruleFunction = {
        //param参数没有使用,仅仅为了对齐参数列表
        notNull: function (param, data) {
            return data != null && (isNaN(data) ? !_.isEmpty(data) : !_.isEmpty(data + ""));
        },
        minLength: function (length, data) {
            return !_.isEmpty(data) || data.length >= length;
        },
        maxLength: function (length, data) {
            return _.isEmpty(data) || data.length <= length;
        },
        minValue: function (value, data) {
            return !isNaN(data) && Number(data) >= value;
        },
        maxValue: function (value, data) {
            return !isNaN(data) && Number(data) <= value;
        },
        regex: function (regex, data) {
            return regex.test(data);
        },
        email: function (regex, data) {
            return ruleFunction.regex(/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,data);
        }
    };

    angular
        .module('com.akxx.aqzyk')
        .service('FormValidate', FormValidate);


    /** @ngInject */
    function FormValidate($q) {
        var self = this;

        //用承诺包一层，仅仅在校验成功后才交付，否则不交付
        self.validateForm = function (rule, data) {
            var deferred = $q.defer();

            if(validateForm(rule,data)){
                //校验成功后，会把data交付给下一层承诺链，便于下一层直接发起请求
                deferred.resolve(data);
            }

            return deferred.promise;  //返回deferred实例的promise对象
        };

        function validateForm(rule, data) {
            if (_.isEmpty(data)) {
                return false;
            }

            for (var i in rule) {
                var ruleObj = rule[i];
                if (!_.isEmpty(ruleObj)) {
                    //noinspection JSDuplicatedDeclaration
                    var thisRule = ruleObj.rule;
                    var thisFilter = ruleObj.filter;
                    for (var j in thisRule) {
                        var key = thisRule[j];
                        var str = data[i];
                        if (!!thisFilter) {
                            str = thisFilter(str);
                        }
                        if (!ruleFunction[key](ruleObj[key], str)) {
                            return false;
                        }
                    }

                }
            }
            return true;
        }

    }

})();
